<template>
  <div class="Bigcontent" :style="{ background: bgc }">
    <!-- 头部 -->
    <header class="header">
      <div class="left" @click="$router.back()"></div>
      <!-- <div class="right">
        <div class="item">
          <img src="../assets/imgs/tingshu.png" alt="" />
          <span>听书</span>
        </div>
        <div class="item">
          <img src="../assets/imgs/download.png" alt="" />
          <span>下载全本</span>
        </div>
      </div> -->
    </header>
    <!-- 头部 -->

    <!-- 书籍信息 -->
    <div class="mains" @click="popup1 = !popup1" v-if="catalog">
      <div class="content">
        <div class="img">
          <img :src="catalog.book.coverImage" alt="" />
        </div>

        <div class="text">
          <div class="title">{{ catalog.book.title }}</div>
          <span class="btn" @click="Payed">免费阅读</span>
        </div>
      </div>
    </div>
    <!-- 书籍信息 -->

    <van-skeleton title :row="4" v-show="isSkeleton" />
    <van-skeleton title :row="5" v-show="isSkeleton" />
    <van-skeleton title :row="3" v-show="isSkeleton" />

    <!-- 章节内容 -->
    <div class="content" @click="popup1 = !popup1" v-show="isPurchased">
      <h1 class="p_content" :style="{ 'font-size': t_fs + 'px' }">
        {{ title }}
      </h1>
      <p
        class="p_content txt-cut"
        :style="{ 'font-size': c_fs + 'px' }"
        v-for="(vl, i) in contentData"
        :key="i"
      >
        {{ vl }}
      </p>
    </div>
    <!-- 章节内容 -->

    <!-- 提示框 -->
    <div class="c_tips" v-if="!isPurchased">
      <div class="box box1" v-show="!isPay">
        <div class="question">
          <p>该章节未解锁</p>
          <p>是否花费 <span>2书豆</span> 解锁该章节?</p>
        </div>
        <div class="btn">
          <div class="no" @click="$router.back()">否</div>
          <div class="yes" @click="pay">是</div>
        </div>
      </div>
      <div class="box box2" v-show="isPay">
        <div class="question">
          <p>书豆余额不足</p>
          <p>是否前往充值页面</p>
        </div>
        <div class="btn">
          <div class="no" @click="$router.back()">否</div>
          <router-link tag="div" to="/recharge" class="yes">是</router-link>
        </div>
      </div>
    </div>
    <!-- 提示框 -->

    <!-- 底部按钮 -->
    <div class="footer_bar" v-if="catalogList">
      <div :class="['item', 'prev', { disabled: disabled <= 0 }]" @click="prev">
        上一章
      </div>
      <div class="item all" @click="popup2 = true">目录</div>
      <div
        :class="[
          'item',
          'next',
          { disabled: disabled == catalogList.length - 1 },
        ]"
        @click="next"
      >
        下一章
      </div>
    </div>
    <!-- 底部按钮 -->

    <!-- 弹出层1 -->
    <van-popup
      v-model="popup1"
      :overlay="false"
      position="bottom"
      :style="{ height: '50px' }"
      class="van-popup1"
    >
      <div class="popup_box" v-if="catalogList">
        <!-- 目录 -->
        <div
          class="item iconfont icon-qita"
          style="font-size: 16px"
          @click="isCatalog"
        ></div>
        <!-- 上一章 -->
        <div :class="['item', { disabled: disabled <= 0 }]" @click="prev">
          上一章
        </div>
        <!-- 下一章 -->
        <div
          :class="['item', { disabled: disabled == catalogList.length - 1 }]"
          @click="next"
        >
          下一章
        </div>
        <!-- 调整字体 -->
        <div class="item" @click="style()">Aa</div>
      </div>
    </van-popup>
    <!-- 弹出层1 -->

    <!-- 弹出层2 -->
    <van-popup
      v-model="popup2"
      :overlay-style="{ 'background-color': 'rgba(0,0,0,.5)' }"
      position="left"
      :style="{ height: '100%', width: '85%' }"
    >
      <div class="catalogView">
        <!-- 头部 -->
        <header class="header">
          <div class="title">目录</div>
        </header>
        <!-- 头部 -->

        <!-- 书籍信息 -->
        <div class="mains line" v-if="catalog">
          <!-- 封面 -->
          <div class="img">
            <img :src="catalog.book.coverImage" alt="" />
          </div>
          <!-- 文本 -->
          <div class="text">
            <div class="title">{{ catalog.book.title }}</div>
            <div class="author">{{ catalog.book.author }}</div>
            <div class="length">共{{ catalog.catalog.length }}章</div>
          </div>
        </div>
        <!-- 书籍信息 -->

        <!-- 目录 -->
        <div class="catalog" v-if="catalog">
          <div
            :class="['item', 'line']"
            v-for="vl in catalogList"
            :key="vl.uuid"
            @click="reader(vl.uuid)"
          >
            {{ vl.title }}
            <div class="lock iconfont icon-mima" v-show="vl.needPay"></div>
          </div>
        </div>
        <!-- 目录 -->
      </div>
    </van-popup>
    <!-- 弹出层2 -->

    <!-- 弹出层3 -->
    <van-popup
      v-model="popup3"
      position="bottom"
      :style="{ height: '22%' }"
      class="van-popup3"
      :overlay-style="{ 'background-color': 'rgba(0,0,0,0)' }"
    >
      <div class="fontSize">
        <div class="label">字号</div>
        <div class="box">
          <div class="btn" @click="fs_reduce">-</div>
          <div class="text">{{ c_fs }}</div>
          <div class="btn" @click="fs_add">+</div>
        </div>
      </div>
      <div class="bgc">
        <div class="label">背景</div>
        <div class="box">
          <div
            :class="['item', { con: vl == bgc }]"
            v-for="(vl, i) in bgcList"
            :key="i"
            :style="{ background: vl }"
            @click="bgc = vl"
          ></div>
        </div>
      </div>
    </van-popup>
    <!-- 弹出层3 -->
  </div>
</template>

<script>
import { getContentData } from "../api/content";
import { getCatalogData } from "../api/details";
export default {
  data() {
    return {
      // todo 关键数据
      bookId: null, //书籍id
      contentId: null, //章节id
      title: "", //章节标题
      contentData: null, //章节内容
      catalog: null, //书籍目录和信息
      catalogList: null, //所有目录
      userInfo: null, //用户数据

      // todo 插件
      popup1: false, //弹出层1章节跳转
      popup2: false, //弹出层2目录
      popup3: false, //弹出层3调整字号
      isSkeleton: true, //骨架屏显示

      // todo
      disabled: 0, // 判断章节切换按钮是否需要禁用
      bgc: "#faf9f7", // 背景颜色
      bgcList: ["#faf9f7", "#fbf5ed", "#e6ebef", "#f5edef"], //所有背景颜色
      t_fs: 30, // 标题的字号
      c_fs: 20, // 内容的字号

      // todo 关键判断条件
      isPurchased: true, // 判断章节是否解锁
      isPay: false, //判断用用户是否意愿充值
    };
  },
  methods: {
    // 获取内容数据
    getContentDataFun() {
      window.scrollTo(0, 0);
      this.contentData = null;
      this.title = "";
      this.isSkeleton = true;

      getContentData({
        source_uuid: this.bookId,
        content_uuid: this.contentId,
      })
        .then((data) => {
          console.log("章节内容==>", data);

          if (data) {
            let arr = data.data.content.split(`<p>`).join("").split(`</p>`);
            arr.splice(arr.length - 1, 1);
            let title = arr[0].split("</h1>");
            arr.splice(0, 1);
            arr.unshift(title[1]);
            this.title = title[0]
              .replaceAll(`<div class="g-book">`, "")
              .replaceAll(`<div class="m-mb">`, "")
              .replaceAll(`<div class="g-book">`, "")
              .replaceAll(`<div class="m-content">`, "")
              .replaceAll(`<h1><span>`, "")
              .replaceAll(`</span>`, "");

            this.contentData = arr;

            this.isSkeleton = false;

            let index = this.catalogList.findIndex(
              (vl) => vl.uuid == this.contentId
            );
            this.disabled = index; // 控制按钮禁用样式

            let userId = localStorage.getItem("userId");

            // 查看是否存在用户
            if (!userId) {
              this.isPurchased = false;
              return;
            }

            // 查看用户是否为VIP
            let isVip = this.userInfo[userId].isVip;

            if (isVip) {
              this.isPurchased = true;
              return;
            }

            // 判断该章节是否购买
            if (index > 4) {
              // 查看书籍id是否存在于用户数据中
              if (this.bookId in this.userInfo[userId].Purchased) {
                // 查看用户数据中是否有该章节id
                let have_id = this.userInfo[userId].Purchased[this.bookId].some(
                  (vl) => vl == this.contentId
                );

                // 如果有该章节id则解锁
                if (have_id) {
                  this.isPurchased = true;
                } else {
                  this.isPurchased = false;
                }
              } else {
                this.isPurchased = false;
                this.userInfo[userId].Purchased[this.bookId] = [];
                localStorage.setItem("userInfo", JSON.stringify(this.userInfo));
              }
            } else {
              this.isPurchased = true;
            }
          }
        })
        .catch(() => {
          this.isSkeleton = false;
        });
    },
    // 获取书籍列表
    getCatalogDataFun() {
      getCatalogData({ source_uuid: this.bookId }).then((data) => {
        this.catalog = data.data;

        this.catalogList = data.data.catalog.filter(
          (vl) => !vl.needPay && "needPay" in vl
        );

        let userId = localStorage.getItem("userId");

        // 查看用户是否为VIP
        let isVip = this.userInfo[userId].isVip;
        if (isVip) {
          this.catalogList.forEach((vl) => {
            vl.needPay = false;
          });
        } else {
          this.catalogList.forEach((vl, i) => {
            let isPay = this.userInfo[userId].Purchased[this.bookId].some(
              (item) => {
                return item == vl.uuid;
              }
            );
            if (i > 4 && !isPay) {
              vl.needPay = true;
            }
          });
        }

        console.log("目录列表==>", this.catalogList);
      });
    },
    // 获取用户数据
    getUserDataFun() {
      this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
    },
    // 下一章
    next() {
      let index = this.catalogList.findIndex((vl) => vl.uuid == this.contentId);

      if (index < this.catalogList.length - 1) {
        index += 1;
        this.contentId = this.catalogList[index].uuid;
        this.disabled = index;
      }
    },
    // 上一章
    prev() {
      let index = this.catalogList.findIndex((vl) => vl.uuid == this.contentId);

      if (index > 0) {
        index -= 1;
        this.disabled = index;
        this.contentId = this.catalogList[index].uuid;
      }
    },
    // 控制目录显示隐藏
    isCatalog() {
      this.popup2 = true;
      this.popup1 = false;
    },
    // 跳转对应章节
    reader(contentId) {
      this.contentId = contentId;
      this.popup2 = false;
    },
    // 改变文本样式
    style() {
      this.popup1 = false;
      this.popup3 = true;
    },
    // 字号增加
    fs_add() {
      if (this.c_fs < 30) {
        this.t_fs += 2;
        this.c_fs += 2;
      }
    },
    // 字号减小
    fs_reduce() {
      if (this.c_fs > 12) {
        this.t_fs -= 2;
        this.c_fs -= 2;
      }
    },
    // 购买
    pay() {
      let userId = localStorage.getItem("userId");
      let balance = this.userInfo[userId].balance;

      if (balance >= 2) {
        this.userInfo[userId].balance -= 2;
        this.userInfo[userId].Purchased[this.bookId].push(this.contentId);
        localStorage.setItem("userInfo", JSON.stringify(this.userInfo));

        this.isPurchased = true;
        this.getCatalogDataFun();

        this.$toast({
          message: "解锁成功",
          position: "bottom",
        });
      } else {
        this.isPay = true;
      }
    },
    Payed() {
      let userId = localStorage.getItem("userId");

      if (this.catalogList) {
        this.catalogList.forEach((vl, i) => {
          let isPay = this.userInfo[userId].Purchased[this.bookId].findIndex(
            (item) => item == vl.uuid
          );
          if (i > 0 && isPay == -1) {
            vl.needPay = true;
            // console.log(vl.title,vl.needPay);
            // this.$set(this.catalogList, "needPay", true);
          }
        });
        console.log(
          this.catalogList,
          this.userInfo[userId].Purchased[this.bookId]
        );
      }
    },
  },
  created() {
    this.bookId = this.$route.query.bookId;
    this.contentId = this.$route.query.contentId;
    this.getUserDataFun(); // 获取用户数据
    this.getCatalogDataFun(); // 获取目录数据
    this.getContentDataFun(); // 获取内容数据
  },
  beforeDestroy() {
    let userId = localStorage.getItem("userId");
    this.userInfo[userId].history[this.bookId] = this.contentId;
    localStorage.setItem("userInfo",JSON.stringify(this.userInfo))
  },
  watch: {
    contentId: function () {
      this.getContentDataFun();
      this.getUserDataFun();
    },
  },
};
</script>

<style lang="scss" scoped>
.Bigcontent {
  min-height: 100%;

  header.header {
    height: 50px;
    text-align: center;
    border-bottom: 2px solid #f0f0f0;

    > .left {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 15px;
      margin: auto;
      transform: rotate(180deg);
      background: url(https://easyreadfs.nosdn.127.net/web/trunk/1533607652166/icon_return.png)
        no-repeat;
      background-size: contain;
      width: 12px;
      height: 20px;
    }

    > .title {
      color: #333;
      font-weight: bold;
      line-height: 50px;
      font-size: 18px;
    }
  }

  header {
    position: sticky;
    top: 0;
    background: #fff;
    display: flex;
    box-sizing: border-box;
    padding: 0 15px;
    width: 100%;
    justify-content: space-between;
    align-items: center;
    z-index: 10;

    > .right {
      display: flex;
      justify-self: flex-end;

      > .item {
        display: flex;
        align-items: center;
        height: 32px;
        padding: 0px 10px;
        background: #f5f5f5;
        margin-left: 10px;
        border-radius: 4px;
        font-size: 14px;
        color: #666;

        > img {
          width: 15px;
          height: 15px;
          margin-right: 5px;
        }
      }
    }
  }

  .mains {
    width: 100%;
    box-sizing: border-box;
    padding: 20px 15px 0;

    .content {
      background: #fff;
      box-shadow: 0 2px 5px 0 rgb(0 0 0 / 10%);
      border-radius: 10px;
      display: flex;
      flex-wrap: wrap;
      box-sizing: border-box;
      padding: 15px 20px;
      width: 100%;

      > .img {
        width: 66px;
        height: 88px;
        margin-right: 15px;

        > img {
          width: 100%;
          height: 100%;
        }
      }

      > .text {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: flex-start;
        font-size: 14px;

        > .btn {
          background-color: #23b383;
          border-radius: 4px;
          height: 27px;
          line-height: 27px;
          font-size: 13px;
          color: #fff;
          text-align: center;
          padding: 0 13px;
        }
      }
    }
  }

  .van-skeleton {
    margin-top: 50px;
  }

  .content {
    width: 100%;
    box-sizing: border-box;
    padding: 30px 20px 180px;
    margin-top: 10px;

    h1 {
      color: #333;
      margin-bottom: 30px;
    }

    p {
      width: 100%;
      font-size: 20px;
      color: #333;
      margin-bottom: 20px;
      line-height: 1.8;
    }
  }

  .c_tips {
    width: 100%;
    height: 280px;
    padding-top: 50px;
    margin-bottom: 60px;

    > .box {
      width: 70%;
      height: 60%;
      margin: auto;
      border: 1px solid #ccc;
      border-radius: 5px;

      > .question {
        height: 75%;
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        align-content: center;
        border-bottom: 1px solid #ccc;

        > p {
          height: 30px;
          width: 100%;
          text-align: center;
          line-height: 30px;
          font-size: 18px;

          > span {
            color: #23b383;
            font-weight: bold;
          }
        }
      }

      > .btn {
        display: flex;
        height: 25%;

        > div {
          flex: 1;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 13px;
          color: #23b383;
          font-weight: bold;

          &:nth-of-type(1) {
            color: #333;
            border-right: 1px solid #ccc;
          }
        }
      }
    }
  }

  .footer_bar {
    // height: 36px;
    display: flex;
    justify-content: space-between;
    width: 100%;
    box-sizing: border-box;
    padding: 20px 14px;

    > .item {
      margin: 0px 6px;
      width: 68px;
      height: 36px;
      line-height: 36px;
      text-align: center;
      font-size: 13px;
      border: solid 1px #ccc;
      padding: 0 15px;

      &.disabled {
        opacity: 0.5;
      }
    }
  }

  .van-popup1 {
    box-shadow: 0px -5px 30px 1px rgba($color: #ccc, $alpha: 0.5);
    > .popup_box {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;

      > .item {
        width: 25%;
        height: 100%;
        font-size: 13px;
        line-height: 50px;
        text-shadow: 3px 3px 5px rgba($color: #333, $alpha: 0.5);
        text-align: center;
        border-right: 1px solid #f0f0f0;

        &.disabled {
          opacity: 0.5;
        }
      }
    }
  }

  .catalogView {
    position: relative;
    min-height: 100%;

    .line::after {
      content: "";
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 1px;
      background: #e4e4e4;
      transform: scaleY(0.5);
    }

    > header.header {
      height: 50px;
      position: sticky;
      top: 0;
      background: #fff;
      z-index: 1000;
      text-align: center;
      border-bottom: 2px solid #f0f0f0;

      > .left {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 15px;
        margin: auto;
        transform: rotate(180deg);
        background: url(https://easyreadfs.nosdn.127.net/web/trunk/1533607652166/icon_return.png)
          no-repeat;
        background-size: contain;
        width: 12px;
        height: 20px;
      }

      > .title {
        color: #333;
        font-weight: bold;
        line-height: 50px;
        font-size: 18px;
      }
    }

    > .mains {
      display: flex;
      padding: 20px;
      position: relative;

      > .img {
        width: 60px;
        height: 80px;
        margin-right: 12px;

        > img {
          width: 100%;
        }
      }

      > .text {
        flex: 1;

        > .title {
          font-size: 15px;
          line-height: 23px;
          font-weight: bold;
        }

        > .author {
          font-size: 12px;
          line-height: 25px;
          color: #999;
        }

        > .length {
          margin-top: 16px;
          font-size: 12px;
          line-height: 12px;
          color: #999;
        }
      }
    }

    > .catalog {
      padding: 0 20px;
      > .item {
        position: relative;
        padding: 18px 0;
        padding-right: 18px;
        font-size: 14px;

        > .lock {
          position: absolute;
          width: 16px;
          height: 16px;
          right: 0;
          top: 0;
          bottom: 0;
          margin: auto;
        }
      }
    }
  }

  .van-popup3 {
    box-sizing: border-box;
    padding: 26px 20px;

    > div {
      display: flex;
      align-items: center;

      > .label {
        font-size: 14px;
        margin-right: 30px;
        color: #333;
      }

      > .box {
        flex: 1;
        display: flex;
        align-items: center;
      }
    }

    > .fontSize {
      margin-bottom: 28px;

      .btn {
        width: 66px;
        height: 27px;
        line-height: 27px;
        border: 1px solid #d9d9d9;
        border-radius: 3px;
        text-align: center;
        font-size: 18px;
      }

      .text {
        flex: 1;
        text-align: center;
        font-size: 16px;
        line-height: 16px;
      }
    }

    > .bgc {
      .item {
        width: 65px;
        height: 28px;
        margin-right: 4px;

        &:last-of-type {
          margin: 0;
        }

        &.con {
          border: 1px solid #23b383;
        }
      }
    }
  }
}
</style>